/*

StrategyMarket.showAllRes()
 */

// 以下这两个需要两两对应
let RES_BUY_AMOUNT_ROOM = {};// storage 数量少于多少挂单买入
let RES_BUY_MAX_PRICE_ROOM = {};// 数量少于多少挂单买入
let RES_BUY_MIN_HOLD_ROOM = {};// 全局库存少于多少买入
(function() {
    (["O","L","H","X","K","Z","U"]).forEach(e=>{
        RES_BUY_AMOUNT_ROOM[e] = 12000
        RES_BUY_MAX_PRICE_ROOM[e] = 0.7
        RES_BUY_MIN_HOLD_ROOM[e] = 100000 // 0.1m
    })
    RES_BUY_MAX_PRICE_ROOM["X"] = 2
    RES_BUY_MAX_PRICE_ROOM["H"] = 1
    RES_BUY_MAX_PRICE_ROOM["U"] = 1
    RES_BUY_MAX_PRICE_ROOM["L"] = 1
})();

let ON_SALE= (function() {
    if(Game.shard.name == "shard3")return{
        [RESOURCE_WIRE]:500
    };

    if(Game.shard.name == "Screeps.Cc")return{
        [RESOURCE_WIRE]:8,
        [RESOURCE_CELL]:8,
        [RESOURCE_ALLOY]:8,
        [RESOURCE_CONDENSATE]:8
    };

    return {}
})();

let allRoomRes = {updateTime:0}

let pro = {
    addStore:(store,b)=> {for(let v in b) if(b[v]>0)store[v]=(store[v]||0)+b[v];return store},
    getStorageTerminalRes:function (room){
        let store = {};
        if(room.storage)pro.addStore(store,room.storage.store)
        if(room.terminal)pro.addStore(store,room.terminal.store)
        if(room.factory)pro.addStore(store,room.factory.store)
        return store
    },
    getMyAllRoomRes:function (){
        let rooms = _.values(Game.rooms).filter(e=>e.my&&e.storage&&e.terminal);
        let all = rooms.reduce((all, room)=> pro.addStore(all,pro.getStorageTerminalRes(room)),{});
        return all;
    },
    showAllRes(){
        let time = Game.cpu.getUsed()
        let all = pro.getMyAllRoomRes()
        // let t = Object.entries(all).sort((a,b)=>b[1]-a[1])
        let t = Object.entries(all).sort((a,b)=> a[0].length==b[0].length?a[0].localeCompare(b[0]):a[0].length-b[0].length)

        // let  = e=> (""+e).split()
        let formatNumber=function (n) {
            var b = parseInt(n).toString();
            var len = b.length;
            if (len <= 3) { return b; }
            var r = len % 3;
            return r > 0 ? b.slice(0, r) + "," + b.slice(r, len).match(/\d{3}/g).join(",") : b.slice(r, len).match(/\d{3}/g).join(",");
        }

        let str = ""
        let arr = t.map(v=>_.padLeft(v[0],10)+":"+_.padLeft(formatNumber(v[1]),10))
        let rowCnt = 5;
        let skip = Math.ceil(arr.length/rowCnt);
        for(let j = 0; j< skip; j++){
            for(let i=0;i<rowCnt;i++){
                let index = j+(i*skip);
                if(index<arr.length) str += arr[index] + (i%rowCnt == rowCnt-1 ?"<br>":" |")
                else str+="<br>"
            }
        }
        console.log(str)
        return "Game.cpu.used:"+(Game.cpu.getUsed() - time)
    },
    getAllOrdersCacheList(resourceType,type){
        if(!Game.market._cache_order){
            Game.market._cache_order = {}
            let allOrders = Game.market.getAllOrders()
            for(let order of allOrders) {
                if (!Game.market._cache_order[order.type]) Game.market._cache_order[order.type] = {}
                if (!Game.market._cache_order[order.type][order.resourceType]) Game.market._cache_order[order.type][order.resourceType] = []
                Game.market._cache_order[order.type][order.resourceType].push(order)
            }
        }
        if(Game.market._cache_order[type]&&Game.market._cache_order[type][resourceType])
            return Game.market._cache_order[type][resourceType];
        else return [];
    },
    exec:function (room){
        if((Game.time)%30!=0)return;//+room.hashCode() 同一 tick 计算，省点 计算需要的 资源
        if(!room.terminal||!room.terminal.my)return;
        if(StationCarry.roomMassStoreCnt(room,RESOURCE_ENERGY)<80000)return;
        if(Game.time - 1500 > allRoomRes.updateTime){
            allRoomRes.res = pro.getMyAllRoomRes();
            allRoomRes.updateTime = Game.time;
        }
        if(!Game.market._dealedOrder)Game.market._dealedOrder = {} // 如果已经交易过了
        let dealed = Game.market._dealedOrder

        // deal 东西
        if(Game.market.credits>100000)
        for(let resType in RES_BUY_AMOUNT_ROOM){
            if(StationCarry.roomMassStoreCnt(room,resType)<RES_BUY_AMOUNT_ROOM[resType]&&(allRoomRes.res[resType]||0)<RES_BUY_MIN_HOLD_ROOM[resType]){
                let sellList = pro.getAllOrdersCacheList(resType,ORDER_SELL)
                let minPrice = 20;
                let minOrder = undefined;
                for(let order of sellList){
                    if(dealed[order.id])break;
                    let energyNeed = Game.market.calcTransactionCost(order.amount,room.name,order.roomName);
                    let totalPrice = energyNeed*0.5 +order.amount*order.price;
                    let price = totalPrice/order.amount;
                    if(price<minPrice){
                        minOrder = order;
                        minPrice = price;
                    }
                }
                // log(minPrice,room.name)
                if(minOrder&&minPrice<RES_BUY_MAX_PRICE_ROOM[resType]){
                    let buyAmount = Math.min(minOrder.amount,10000)
                    let code = Game.market.deal(minOrder.id,buyAmount,room.name);
                    log("buy : ",resType,buyAmount,minPrice,minOrder.id,code,room.name);
                    dealed[minOrder.id] = true;
                    return;// 交易后直接停止本轮交易
                }
            }
        }

        // 卖东西
        if(Game.market.credits<10000000)
        for(let resType in ON_SALE){
            if(!room.terminal.store[resType])continue;
            let buyList = pro.getAllOrdersCacheList(resType,ORDER_BUY)
            for(let order of buyList){
                if(dealed[order.id])break;
                let maxPrice = ON_SALE[resType];
                let maxOrder = undefined;
                for(let order of buyList){
                    if(dealed[order.id])break;
                    let energyNeed = Game.market.calcTransactionCost(order.amount,room.name,order.roomName);
                    let totalPrice = -energyNeed*0.5 +order.amount*order.price;
                    let price = totalPrice/order.amount;
                    if(price>=maxPrice){
                        maxOrder = order;
                        maxPrice = price;
                    }
                }
                // log(maxPrice,room.name,maxOrder)
                if(maxOrder&&maxPrice>=ON_SALE[resType]){
                    let sellAmount = Math.min(maxOrder.amount,room.terminal.store[resType])
                    let code = Game.market.deal(maxOrder.id,sellAmount,room.name);
                    log("sell: ",resType,sellAmount,maxPrice,maxOrder.id,code,room.name);
                    dealed[maxOrder.id] = true;
                    return;// 交易后直接停止本轮交易
                }

            }
        }

    }
}


global.StrategyMarket=pro;